package Screen
{
	import Button.UglyButton;
	import Button.UglyCheckBox;
	import Button.UglyTextField;
	
	import Const.*;
	
	import Ecuations.MinTime;
	
	import Global.GlobalClass;
	
	import InfoGroup.ErrorMessage;
	import InfoGroup.SectorOutputData;
	
	import Screen.GenericScreen;
	
	import Train.*;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	import flash.utils.setTimeout;
	
	import flashx.textLayout.elements.GlobalSettings;
	
	public final class ResultScreen extends GenericScreen
	{		
		private var _calculateButton : UglyButton;
		
		private var _nextSector : UglyButton;
		private var _prevSector : UglyButton;
		private var _showButton : Boolean = true;
		private var _actualSectorIndex : int = 0;
		
		private var _outputSectorList : Vector.<SectorOutputData> = new Vector.<SectorOutputData>;		
		private var _actualOutputSector : SectorOutputData;
		
		private var _velFunProgresiva : UglyButton;
		private var _velFunTiempo     : UglyButton;
		private var _acelFunTiempo    : UglyButton;
		private var _posFunTiempo     : UglyButton;
		private var _ShowTables       : UglyButton;		
		
		//Const
		public const SECTOROUTPUT_POSX : int = 80;
		public const SECTOROUTPUT_POSY : int = 100;
		
		private var tableAvailable : Boolean = false;
		
		//Checkbox
		private var _cargoTrainCheck : UglyCheckBox;
		private var _passengerTrainCheck : UglyCheckBox;
		
		private var _minTimeCheck 			   : UglyCheckBox;
		private var _minFuelCheck 			   : UglyCheckBox; //Maxima Deriva
		private var _travelTimeless50AndMaxDer : UglyCheckBox;
		
		//For Graphics
		private var _graphicScreen_1 : GraphicScreen;
		private var _graphicScreen_2 : GraphicScreen;
		private var _graphicScreen_3 : GraphicScreen;
		private var _graphicScreen_4 : GraphicScreen;		
		
		private var _actualGraphicScreen : GraphicScreen;		
		private var _inTable : Boolean = true;
		
		//Error
		private var _errorMessage : ErrorMessage;
		private var _addedErrorMessage : Boolean = false;
		private var _removeButtonInError : Boolean = false;
		//private
		
		private var tmpTrain : BaseTrain;
		private var doThis:Boolean = true;
		public function ResultScreen()
		{
			super();
			
			_calculateButton = new UglyButton("Calcular", ButtonIDs.BUTTONID_CALCULATE);
			_calculateButton.setPos(10, 10);
			_calculateButton.addEventListener(MouseEvent.CLICK, calculateAndShowResult);		
			addChild(_calculateButton);
			
			_prevSector = new UglyButton("Anterior", ButtonIDs.BUTTONID_PREV);
			_prevSector.setPos(10, 500);
			_prevSector.addEventListener(MouseEvent.CLICK, changeSectorToShow);
			
			_nextSector = new UglyButton("Siguiente", ButtonIDs.BUTTONID_NEXT);
			_nextSector.setPos(10, 530);
			_nextSector.addEventListener(MouseEvent.CLICK, changeSectorToShow);	
			
			//Creates more buttons
			var buttonsXPos : int = 690;
			var buttonsYPos : int = 350;
			var buttonsYOffset : int = 40;
			
			_velFunProgresiva = new UglyButton("Vel.Fun.Prog", ButtonIDs.BUTTONID_SPEEDFPROG);
			_velFunProgresiva.addEventListener(MouseEvent.CLICK, changeToShow);
			_velFunProgresiva.x = buttonsXPos;
			_velFunProgresiva.y = buttonsYPos;
				
			_velFunTiempo = new UglyButton("Vel.Fun.T", ButtonIDs.BUTTONID_SPEEDFTIME);
			_velFunTiempo.addEventListener(MouseEvent.CLICK, changeToShow);
			_velFunTiempo.x = buttonsXPos;
			_velFunTiempo.y = _velFunProgresiva.y + buttonsYOffset;
				
			_acelFunTiempo = new UglyButton("Acel.Fun.T", ButtonIDs.BUTTONID_ACELLFTIME);
			_acelFunTiempo.addEventListener(MouseEvent.CLICK, changeToShow);
			_acelFunTiempo.x = buttonsXPos;
			_acelFunTiempo.y = _velFunTiempo.y + buttonsYOffset;
				
			_posFunTiempo = new UglyButton("Pos.Fun.T", ButtonIDs.BUTTONID_POSFTIME);
			_posFunTiempo.addEventListener(MouseEvent.CLICK, changeToShow);
			_posFunTiempo.x = buttonsXPos;
			_posFunTiempo.y = _acelFunTiempo.y + buttonsYOffset;
				
			_ShowTables = new UglyButton("Tablas", ButtonIDs.BUTTONID_SHOWTABLE);
			_ShowTables.addEventListener(MouseEvent.CLICK, changeToShow);
			_ShowTables.x = buttonsXPos;
			_ShowTables.y = _posFunTiempo.y + buttonsYOffset;
			
			//CheckBox
			_cargoTrainCheck  = new UglyCheckBox("Carga", CheckBoxIDs.CHECKBOXID_CARGO_TRAIN);
			_cargoTrainCheck.x = 200;
			_cargoTrainCheck.y = 10;
			_cargoTrainCheck.addEventListener(MouseEvent.CLICK, checkBoxFunction);
			addChild(_cargoTrainCheck);
			
			_passengerTrainCheck  = new UglyCheckBox("Pasajeros", CheckBoxIDs.CHECKBOXID_PASSENGER_TRAIN);
			_passengerTrainCheck.x = 200;
			_passengerTrainCheck.y = 40;
			_passengerTrainCheck.addEventListener(MouseEvent.CLICK, checkBoxFunction);
			addChild(_passengerTrainCheck);
			
			_minTimeCheck = new UglyCheckBox("T. Minimo", CheckBoxIDs.CHECKBOXID_MIN_TIME);
			_minTimeCheck.x = 400;
			_minTimeCheck.y = 10;
			_minTimeCheck.addEventListener(MouseEvent.CLICK, checkBoxFunction);
			addChild(_minTimeCheck);
			
			_minFuelCheck = new UglyCheckBox("Min. Comb.", CheckBoxIDs.CHECKBOXID_MIN_FUEL); //Maxima Deriva
			_minFuelCheck.x = 400;
			_minFuelCheck.y = 40;
			_minFuelCheck.addEventListener(MouseEvent.CLICK, checkBoxFunction);
			addChild(_minFuelCheck);
			
			_travelTimeless50AndMaxDer = new UglyCheckBox("Max.D.50%T.Min", CheckBoxIDs.CHECKBOXID_LESS_50P);
			_travelTimeless50AndMaxDer.x = 550;
			_travelTimeless50AndMaxDer.y = 10;
			_travelTimeless50AndMaxDer.addEventListener(MouseEvent.CLICK, checkBoxFunction);
			addChild(_travelTimeless50AndMaxDer);
			
			_errorMessage = new ErrorMessage();
			_errorMessage.x = 200;
			_errorMessage.y = 300; //_errorMessage.setError(ErrorIDs.ERRORID_VELMAX);
			//addChild(_errorMessage);
		}
		
		private function changeToShow(evt:MouseEvent) : void
		{
			switch(evt.target.valueOf().getId())
			{
				case ButtonIDs.BUTTONID_SPEEDFPROG:
					if(tableAvailable)
					{
						removeChild(_actualOutputSector);
						removeChild(_prevSector);
						removeChild(_nextSector);
						tableAvailable = false;
					}
					
					if(_actualGraphicScreen != _graphicScreen_1)
					{
						if(_actualGraphicScreen != null)
							removeChild(_actualGraphicScreen);
						
						_actualGraphicScreen = _graphicScreen_1;
						addChild(_actualGraphicScreen);
						
						_actualGraphicScreen.x = SECTOROUTPUT_POSX;
						_actualGraphicScreen.y = SECTOROUTPUT_POSY;
						
						//_actualGraphicScreen.velocidadEnFuncionDelLaProgresiva();
					}
					break;
				case ButtonIDs.BUTTONID_SPEEDFTIME:
					if(tableAvailable)
					{
						removeChild(_actualOutputSector);
						removeChild(_prevSector);
						removeChild(_nextSector);
						tableAvailable = false;
					}
					
					if(_actualGraphicScreen != _graphicScreen_2)
					{
						if(_actualGraphicScreen != null)
							removeChild(_actualGraphicScreen);
						
						_actualGraphicScreen = _graphicScreen_2;
						addChild(_actualGraphicScreen);
						
						_actualGraphicScreen.x = SECTOROUTPUT_POSX;
						_actualGraphicScreen.y = SECTOROUTPUT_POSY;
						
						//_actualGraphicScreen.velocidadEnFuncionDelTiempo();
					}
					break;
				case ButtonIDs.BUTTONID_ACELLFTIME:
					if(tableAvailable)
					{
						removeChild(_actualOutputSector);
						removeChild(_prevSector);
						removeChild(_nextSector);
						tableAvailable = false;
					}
					
					if(_actualGraphicScreen != _graphicScreen_3)
					{
						if(_actualGraphicScreen != null)
							removeChild(_actualGraphicScreen);
						
						_actualGraphicScreen = _graphicScreen_3;
						addChild(_actualGraphicScreen);
						
						_actualGraphicScreen.x = SECTOROUTPUT_POSX;
						_actualGraphicScreen.y = SECTOROUTPUT_POSY;
						
						//_actualGraphicScreen.aceleracionEnFuncionDelTiempo();
					}
					break;
				case ButtonIDs.BUTTONID_POSFTIME:					
					if(tableAvailable)
					{
						removeChild(_actualOutputSector);
						removeChild(_prevSector);
						removeChild(_nextSector);
						tableAvailable = false;
					}
					
					if(_actualGraphicScreen != _graphicScreen_4)
					{
						if(_actualGraphicScreen != null)
							removeChild(_actualGraphicScreen);
						
						_actualGraphicScreen = _graphicScreen_4;
						addChild(_actualGraphicScreen);
						
						_actualGraphicScreen.x = SECTOROUTPUT_POSX;
						_actualGraphicScreen.y = SECTOROUTPUT_POSY;
						
						//_actualGraphicScreen.posicionEnFuncionDelTiempo();
					}								
					break;				
				
				case ButtonIDs.BUTTONID_SHOWTABLE:
					if(!tableAvailable)
					{
						addChild(_actualOutputSector);
						addChild(_prevSector);
						addChild(_nextSector);
						tableAvailable = true;
						
						removeChild(_actualGraphicScreen); //Remove the graphic screen
						
						_actualGraphicScreen = null;
					}
					break;
			}
			if (_actualGraphicScreen) 
			{
				stage.addEventListener(KeyboardEvent.KEY_DOWN, onMoveGraphic);
				_actualGraphicScreen.mouseEnabled = false;
				
			}
		}
		
		//LLAMAME CUANDO SAQUE EL GRAFICO DE LA PANTALLA!
		public function removeListener() : void 
		{
			stage.removeEventListener(KeyboardEvent.KEY_DOWN, onMoveGraphic);
		}
		
		private function onMoveGraphic(e:KeyboardEvent) : void
		{
			switch(e.keyCode)
			{
				case Keyboard.LEFT:
					_actualGraphicScreen.x -= 22.5;
					break;
				case Keyboard.RIGHT:
					_actualGraphicScreen.x += 22.5;
					break;
				case Keyboard.UP:
					_actualGraphicScreen.y -= 22.5;
					break;
				case Keyboard.DOWN:
					_actualGraphicScreen.y += 22.5;
					break;
				case Keyboard.NUMPAD_ADD:
					_actualGraphicScreen.scaleX += 0.5;
					_actualGraphicScreen.scaleY += 0.5;
					_actualGraphicScreen.scaleMarkers( -0.1 );
					_actualGraphicScreen.x = SECTOROUTPUT_POSX;
					_actualGraphicScreen.y = SECTOROUTPUT_POSY;
					break;
				case Keyboard.NUMPAD_SUBTRACT:
					_actualGraphicScreen.scaleX -= 0.5;
					_actualGraphicScreen.scaleY -= 0.5;
					_actualGraphicScreen.scaleMarkers( 0.1 );
					_actualGraphicScreen.x = SECTOROUTPUT_POSX;
					_actualGraphicScreen.y = SECTOROUTPUT_POSY;
					break;
					
					
			}
		}
		
		private function changeSectorToShow(evt:MouseEvent) : void
		{
			switch(evt.target.valueOf().getId())
			{
				case ButtonIDs.BUTTONID_PREV:
					removeChild(_actualOutputSector);
					
					_actualSectorIndex--;
					if(_actualSectorIndex < 0)
						_actualSectorIndex = _outputSectorList.length - 1;
					
					_actualOutputSector = _outputSectorList[_actualSectorIndex];
					_actualOutputSector.x = SECTOROUTPUT_POSX;
					_actualOutputSector.y = SECTOROUTPUT_POSY;
					
					addChild(_actualOutputSector);
					break;
				case ButtonIDs.BUTTONID_NEXT:
					removeChild(_actualOutputSector);
					
					_actualSectorIndex++;
					if(_actualSectorIndex >= _outputSectorList.length)
						_actualSectorIndex = 0;
					
					_actualOutputSector = _outputSectorList[_actualSectorIndex];
					_actualOutputSector.x = SECTOROUTPUT_POSX;
					_actualOutputSector.y = SECTOROUTPUT_POSY;
					
					addChild(_actualOutputSector);
					break;
			}
			if(_actualSectorIndex == _outputSectorList.length-1)
				_actualOutputSector.showTotalTime(true);
			else
				_actualOutputSector.showTotalTime(false);
		}		
		
		//ACA HACE LOS CALCULO
		private function calculate() : void
		{				
			var sectorList:Array = DistanceObjCreator.stationsList; //Get all Sectors			
			//Select Ecuation				
			if(_minTimeCheck.isActive()){ //NACHOOOOOOO ACA TENES QUE PONER LAS DIFERENTES ECUACIONES :)
				trace("TIEMPO MINIMO");
				basicCalculation(false, tmpTrain);
			}
			else if (_minFuelCheck.isActive()){
				trace("MINIMO COMBUSTIBLE");
				basicCalculation(true, tmpTrain);
			}
			else if(_travelTimeless50AndMaxDer.isActive()){
				trace("MAXIMA DERIVA 50% Tiempo");
				doThis = true;
				calculateTimeShit(0, false, tmpTrain );
				
			}						
				
			_graphicScreen_1 = null;
			_graphicScreen_2 = null;
			_graphicScreen_3 = null;
			_graphicScreen_4 = null;
			
			//Create objects to graphic
			_graphicScreen_1 = new GraphicScreen(sectorList, GlobalClass.totalObjList);
			_graphicScreen_1.velocidadEnFuncionDelLaProgresiva();
			_graphicScreen_2 = new GraphicScreen(sectorList, GlobalClass.totalObjList);
			_graphicScreen_2.velocidadEnFuncionDelTiempo();
			_graphicScreen_3 = new GraphicScreen(sectorList, GlobalClass.totalObjList);
			_graphicScreen_3.aceleracionEnFuncionDelTiempo();
			_graphicScreen_4 = new GraphicScreen(sectorList, GlobalClass.totalObjList);
			_graphicScreen_4.posicionEnFuncionDelTiempo();
			
			_actualGraphicScreen = null;
		}
		
		private function calculateAndShowResult(evt:MouseEvent) : void
		{
			trace("CALCULAR Y MOSTRAR");
			
			//Remove all before show again
			if(_outputSectorList.length > 0)
			{
				if(tableAvailable)
					removeChild(_actualOutputSector);
				else
					removeChild(_actualGraphicScreen);
				
				_showButton = true;
				for(var i:int = 0; i < _outputSectorList.length; i++)
				{
					_outputSectorList[i].clearDeltaXList();
				}
				_outputSectorList.splice(0, _outputSectorList.length);
			}			
			
			if(!_cargoTrainCheck.isActive() && !_passengerTrainCheck.isActive())
			{
				showError(ErrorIDs.ERRORID_NOTRAIN);							
			}
			else
			{				
				if(!_minTimeCheck.isActive() && !_minFuelCheck.isActive() && !_travelTimeless50AndMaxDer.isActive())
				{				
					showError(ErrorIDs.ERRORID_NOECUA);
				}
				else
				{
					//Select the Train			
					if(_cargoTrainCheck.isActive())
					{
						tmpTrain = GlobalClass.cargoTrain;					
					}
					else if(_passengerTrainCheck.isActive())
					{
						tmpTrain = GlobalClass.passengerTrain;				
					}
					
					//Check if distance = 0
					var distanceWithZero : Boolean = false;					
					var tmpStationList:Array = DistanceObjCreator.stationsList;
					
					for (var j:int = 0; j < tmpStationList.length; j++)
					{
						if((tmpStationList[j].initPos == 0 && j > 0) || tmpStationList[j].destPos == 0)
						{
							distanceWithZero = true;
							break;
						}
					}
					
					//Check if sector vMax = 0
					var sectorVMaxZero : Boolean = false;	
					for (var x:int = 0; x < tmpStationList.length; x++)
					{
						if(tmpStationList[x].segmentVMax == 0)
						{
							sectorVMaxZero = true;
							break;
						}
					}
					
					//First verified if all data is fine
					if(tmpTrain.accel == 0 || tmpTrain.brakeAccel == 0 || tmpTrain.trainVMax == 0
						|| tmpTrain.deriveAccel == 0)
					{						
						showError(ErrorIDs.ERRORID_VALUESIN0);
					}
					//else if(tmpTrain.deriveAccel >= tmpTrain.brakeAccel) //TENGO DUDAS ACA
					else if(Math.abs(tmpTrain.deriveAccel) >= Math.abs(tmpTrain.brakeAccel))
					{
						showError(ErrorIDs.ERRORID_ACELDER);				
					}
					else if(distanceWithZero)
					{						
						showError(ErrorIDs.ERRORID_DISTZERO);
					}
					else if(sectorVMaxZero)
					{
						showError(ErrorIDs.ERRORID_VMAXSECTOR);
					}
					else if(tmpStationList.length == 0)
					{
						showError(ErrorIDs.ERRORID_NOSTATION);
					}
					else //ALL OK
					{						
						//Clean the DataObject total list
						GlobalClass.totalObjList.splice(0, GlobalClass.totalObjList.length);
						
						//Do all the calcule
						calculate();			
						
						//Show the table
						if(_outputSectorList.length > 0)
						{				
							_actualSectorIndex = 0;
							_actualOutputSector = _outputSectorList[_actualSectorIndex];
							
							_actualOutputSector.x = SECTOROUTPUT_POSX;
							_actualOutputSector.y = SECTOROUTPUT_POSY;
							
							addChild(_actualOutputSector);
							
							tableAvailable = true;
						}
						
						//Add next/prev buttons
						if(_showButton)
						{
							addChild(_prevSector);
							addChild(_nextSector);				
							
							addChild(_velFunProgresiva);
							addChild(_velFunTiempo);
							addChild(_acelFunTiempo);
							addChild(_posFunTiempo);
							addChild(_ShowTables);
							
							_showButton = false;
							_removeButtonInError = true;
						}
						
						//Close if any error
						closeError();
						
						//Show total Time
						if(_actualSectorIndex == _outputSectorList.length-1)
							_actualOutputSector.showTotalTime(true);
						else
							_actualOutputSector.showTotalTime(false);
					}
				}
			}			
		}
		
		
		//esto es para el porcentage y esa mierda
		private function calculateTimeShit(percentage:Number=0, useAlternativeFunction:Boolean=false, trainType:BaseTrain=null) : void
		{
			var totalTimeMinTime:Number = 0;
			var totalTimeMaxDerive:Number = 0;
			
			//estos dos son para sacar desp el delta q se va a ir modificando segun un %
			var deltaMinTime:Number = 0;
			var deltaDerive:Number = 0;
			
			var sectorList:Array = DistanceObjCreator.stationsList; //Get all Sectors			
			
			var usedEccs:Array = new Array();
			
			var finalPos:Number = 0;
			
			for (var i:int = 0; i < sectorList.length; i++)
			{				
				//CAMBIAR LO DEL TREN
				var station:DistanceObject = sectorList[i];
				var useEcc:MinTime = new MinTime(trainType, sectorList[i], sectorList[i-1], this.stage, finalPos );
				finalPos += sectorList[i].destPos;
				
				if (!station.trainStops)
				{
					station.trainInitVelocity = sectorList[i - 1] ? sectorList[i - 1].trainFinalVelocity : 0;
					station.trainFinalVelocity = sectorList[i + 1] ? sectorList[i + 1].segmentVMax : 0;
					
					useEcc.calculate( MinTime.USE_MIN_TIME, station.trainInitVelocity, station.trainFinalVelocity, finalPos);
					totalTimeMinTime += useEcc.getSectorTotalTime();
					
				}
				else
				{
					station.trainInitVelocity = sectorList[i - 1] ? sectorList[i - 1].trainFinalVelocity : 0;
					useEcc.calculate( MinTime.USE_MIN_TIME, station.trainInitVelocity, 0, finalPos);
					totalTimeMinTime += useEcc.getSectorTotalTime();
				}
				
				
				if (useAlternativeFunction)
					deltaMinTime = useEcc.getDeltaToModify();
				
				var useEccDerive:MinTime = new MinTime( trainType, sectorList[i], sectorList[i-1], this.stage, finalPos );
				
				if (useAlternativeFunction)
					useEccDerive.usePercentageChange(percentage, deltaMinTime);
				
			
				
				if (!station.trainStops)
				{
					station.trainInitVelocity = sectorList[i - 1] ? sectorList[i - 1].trainFinalVelocity : 0;
					station.trainFinalVelocity = sectorList[i + 1] ? sectorList[i + 1].segmentVMax : 0;
					
					useEccDerive.calculate(MinTime.USE_MAX_DERIVE, station.trainInitVelocity, station.trainFinalVelocity, finalPos);
					totalTimeMaxDerive += useEccDerive.getSectorTotalTime();	
				}
				else 
				{
					station.trainInitVelocity = sectorList[i - 1] ? sectorList[i - 1].trainFinalVelocity : 0;
					useEccDerive.calculate( MinTime.USE_MAX_DERIVE, station.trainInitVelocity, 0, finalPos);
					totalTimeMaxDerive += useEccDerive.getSectorTotalTime();
				}
				
				trace("BLABLABKLA : " + totalTimeMaxDerive );
				usedEccs.push( useEccDerive );
				
			}
			
			var limitTime:Number = totalTimeMinTime/2;
			
			if (totalTimeMaxDerive > limitTime)
			{
				percentage += 1;
				if (percentage > 100)
					return;
				
				calculateTimeShit(percentage, true, trainType);
			}
			
			if (doThis) //para evitar q esto de aca se haga cuando empieza a volver de la recursividad (??)
			{
				GlobalClass.travelTotalTime = totalTimeMaxDerive/3600;
				
				//Fill Sectors values
				for (var x:int = 0; x < usedEccs.length; x++)
				{				
					var tmpOuputSector : SectorOutputData = new SectorOutputData();
					tmpOuputSector.setSectorNumber(x + 1);
					
				
					for(var j:int = 0; j < usedEccs[x].dataObjectList.length; j++)
					{						
						tmpOuputSector.addDeltaX(j, usedEccs[x].dataObjectList[j].velocity, usedEccs[x].dataObjectList[j].time, usedEccs[x].dataObjectList[j].accel, usedEccs[x].dataObjectList[j].deltaX);
						tmpOuputSector.timeStopedField.setText(usedEccs[x].dataObjectList[j].timeStopped);
					
						trace((String)(usedEccs[x].dataObjectList[j].velocity));
					}
					//Show travel total time
					tmpOuputSector.totalTimeField.setText((String)(GlobalClass.travelTotalTime));
				
					_outputSectorList.push(tmpOuputSector);
				
					//Save all the DataObjects - Uses for graphics					
					for(var k:int = 0; k < usedEccs[x].dataObjectList.length; k++)
					{
						GlobalClass.totalObjList.push( usedEccs[x].dataObjectList[k] );
					}
				}
				doThis = false;
			}
		}

		
		private function basicCalculation(useMaxDerive:Boolean, trainType:BaseTrain=null) : void
		{
			var sectorList:Array = DistanceObjCreator.stationsList; //Get all Sectors			
			
			//calculateTimeShit();
			var totalTime:Number = 0;
			var finalPos:Number = 0;
			for (var i:int = 0; i < sectorList.length; i++)
			{				
				var station:DistanceObject = sectorList[i];
				var useEcc:MinTime = new MinTime( trainType, sectorList[i], sectorList[i-1] ,this.stage, finalPos );
				
				if (!station.trainStops)
				{
					station.trainInitVelocity = sectorList[i - 1] ? sectorList[i - 1].trainFinalVelocity : 0;
					station.trainFinalVelocity = sectorList[i + 1] ? sectorList[i + 1].segmentVMax : 0;
				
					finalPos += sectorList[i].destPos;
					useEcc.calculate( useMaxDerive ? MinTime.USE_MAX_DERIVE : MinTime.USE_MIN_TIME, station.trainInitVelocity, station.trainFinalVelocity, finalPos);
					totalTime += useEcc.getSectorTotalTime();
				}
				else 
				{
					station.trainInitVelocity = sectorList[i - 1] ? sectorList[i - 1].trainFinalVelocity : 0;
					finalPos += sectorList[i].destPos;
					useEcc.calculate( useMaxDerive ? MinTime.USE_MAX_DERIVE : MinTime.USE_MIN_TIME, station.trainInitVelocity, 0, finalPos);
					totalTime += useEcc.getSectorTotalTime();
				}
				
				//THIS IS ONLY FOR OUTPUT
				//Create Sectors
				var tmpOuputSector : SectorOutputData = new SectorOutputData();
				tmpOuputSector.setSectorNumber(i + 1);
				//Fill Sectors values
				for(var j:int = 0; j < useEcc.dataObjectList.length; j++)
				{						
					tmpOuputSector.addDeltaX(j, useEcc.dataObjectList[j].velocity, useEcc.dataObjectList[j].time, useEcc.dataObjectList[j].accel, useEcc.dataObjectList[j].deltaX);
					tmpOuputSector.timeStopedField.setText(useEcc.dataObjectList[j].timeStopped);						
				}
				
				GlobalClass.travelTotalTime = totalTime/3600;
				
				//Show travel total time
				tmpOuputSector.totalTimeField.setText((String)(GlobalClass.travelTotalTime));
				
				_outputSectorList.push(tmpOuputSector);
				
				//Save all the DataObjects - Uses for graphics					
				for(var k:int = 0; k < useEcc.dataObjectList.length; k++)
				{
					GlobalClass.totalObjList.push( useEcc.dataObjectList[k] );
				}
			} //For
			
		}

		
		private function checkBoxFunction(evt:MouseEvent): void
		{
			switch(evt.target.valueOf().getId())
			{
				case CheckBoxIDs.CHECKBOXID_PASSENGER_TRAIN:
					_cargoTrainCheck.activate(false);
					_passengerTrainCheck.activate(true);
					break;
				case CheckBoxIDs.CHECKBOXID_CARGO_TRAIN:
					_cargoTrainCheck.activate(true);
					_passengerTrainCheck.activate(false);
					break;
				
				case CheckBoxIDs.CHECKBOXID_MIN_TIME:
					_minTimeCheck.activate(true);
					_minFuelCheck.activate(false);
					_travelTimeless50AndMaxDer.activate(false);
					break;
				case CheckBoxIDs.CHECKBOXID_MIN_FUEL:
					_minTimeCheck.activate(false);
					_minFuelCheck.activate(true);
					_travelTimeless50AndMaxDer.activate(false);
					break;
				case CheckBoxIDs.CHECKBOXID_LESS_50P:
					_minTimeCheck.activate(false);
					_minFuelCheck.activate(false);
					_travelTimeless50AndMaxDer.activate(true);
					break;				
			}			
		}
		
		private function showError(errorId : int) : void
		{
			_errorMessage.setError(errorId);
			
			if(!_addedErrorMessage)
			{
				addChild(_errorMessage);
				_addedErrorMessage = true;
			}			
			
			if(_removeButtonInError)
			{
				removeChild(_prevSector);
				removeChild(_nextSector);				
				
				removeChild(_velFunProgresiva);
				removeChild(_velFunTiempo);
				removeChild(_acelFunTiempo);
				removeChild(_posFunTiempo);
				removeChild(_ShowTables);
				
				_removeButtonInError = false;
			}
		}
		
		private function closeError() : void
		{
			if(_addedErrorMessage)
			{
				removeChild(_errorMessage);
				_addedErrorMessage = false;
			}			
		}

	}
}